package ynu.edu.elmservlet.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import ynu.edu.elmservlet.po.Cart;
import ynu.edu.elmservlet.service.CartService;
import ynu.edu.elmservlet.service.impl.CartServiceImpl;
import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

public class CartController {
    private final ObjectMapper objectMapper = new ObjectMapper();

    private Map<String, Object> getRequestData(HttpServletRequest request) throws Exception {
        String contentType = request.getContentType();
        String method = request.getMethod();
        
        System.out.println("Request Method: " + method);
        System.out.println("Content Type: " + contentType);
        
        Map<String, Object> data = new HashMap<>();
        
        // 对于 PUT 和 DELETE 请求，需要从请求体中读取数据
        if ("PUT".equalsIgnoreCase(method) || "DELETE".equalsIgnoreCase(method)) {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String requestBody = sb.toString();
            System.out.println("Request Body: " + requestBody);
            
            // 使用 URLDecoder 解码请求体
            String decodedBody = java.net.URLDecoder.decode(requestBody, "UTF-8");
            System.out.println("Decoded Body: " + decodedBody);
            
            // 解析 form-urlencoded 格式的数据
            String[] pairs = decodedBody.split("&");
            for (String pair : pairs) {
                int idx = pair.indexOf("=");
                if (idx > 0) {
                    String key = pair.substring(0, idx);
                    String value = pair.substring(idx + 1);
                    data.put(key, value);
                }
            }
        } else {
            // 对于其他请求，使用 getParameter 获取参数
            request.getParameterMap().forEach((key, value) -> {
                if (value != null && value.length > 0) {
                    data.put(key, value[0]);
                }
            });
        }
        
        System.out.println("Parsed Data: " + data);
        return data;
    }

    public Object saveCart(HttpServletRequest request) throws Exception {
        try {
            Map<String, Object> data = getRequestData(request);
            System.out.println("Received data: " + data);
            
            Cart cart = new Cart();
            cart.setUserId((String) request.getAttribute("userId"));
            cart.setBusinessId(Integer.valueOf(data.get("businessId").toString()));
            cart.setFoodId(Integer.valueOf(data.get("foodId").toString()));
            
            CartService service = new CartServiceImpl();
            int result = service.saveCart(cart);
            
            // 直接返回数据库操作的结果
            return result;
        } catch (Exception e) {
            System.out.println("Save cart error: " + e.getMessage());
            return 0;
        }
    }

    public Object updateCart(HttpServletRequest request) throws Exception {
        try {
            Map<String, Object> data = getRequestData(request);
            System.out.println("Update cart data: " + data);
            
            // 获取用户ID
            String userId = (String) request.getAttribute("userId");
            if (userId == null || userId.trim().isEmpty()) {
                System.out.println("User ID is missing");
                return 0;
            }
            
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setBusinessId(Integer.valueOf(data.get("businessId").toString()));
            cart.setFoodId(Integer.valueOf(data.get("foodId").toString()));
            cart.setQuantity(Integer.valueOf(data.get("quantity").toString()));
            
            CartService service = new CartServiceImpl();
            int result = service.updateCart(cart);
            
            System.out.println("Update cart result: " + result);
            return result;
        } catch (Exception e) {
            System.out.println("Update cart error: " + e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }

    public Object removeCart(HttpServletRequest request) throws Exception {
        try {
            Map<String, Object> data = getRequestData(request);
            System.out.println("Remove cart data: " + data);
            
            // 获取用户ID
            String userId = (String) request.getAttribute("userId");
            if (userId == null || userId.trim().isEmpty()) {
                System.out.println("User ID is missing");
                return 0;
            }
            
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setBusinessId(Integer.valueOf(data.get("businessId").toString()));
            cart.setFoodId(Integer.valueOf(data.get("foodId").toString()));
            
            CartService service = new CartServiceImpl();
            int result = service.removeCart(cart);
            
            System.out.println("Remove cart result: " + result);
            return result;
        } catch (Exception e) {
            System.out.println("Remove cart error: " + e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }

    public Object listCart(HttpServletRequest request) throws Exception {
        try {
            String userId = (String) request.getAttribute("userId");
            String businessId = request.getParameter("businessId");
            
            Cart cart = new Cart();
            cart.setUserId(userId);
            if (businessId != null && !businessId.trim().isEmpty()) {
                cart.setBusinessId(Integer.valueOf(businessId));
            }
            
            CartService service = new CartServiceImpl();
            List<Cart> list = service.listCart(cart);
            
            // 直接返回列表数据，不要包装在 response 对象中
            return list;
        } catch (Exception e) {
            System.out.println("List cart error: " + e.getMessage());
            e.printStackTrace();
            // 返回空数组而不是错误对象
            return new ArrayList<>();
        }
    }
}